I have a table Orders and I need to combine multiple rows for the same
CustomerID into a single row, concatenating the OrderIDs. Can someone assist me?
home / developersection / forums / help with writing a query to combine multiple rows into one in sql server
I have a table Orders and I need to combine multiple rows for the same
CustomerID into a single row, concatenating the OrderIDs. Can someone assist me?
Ravi Vishwakarma
16-Jul-2024Combining multiple rows into one in SQL Server can be achieved using the
STRING_AGGfunction (available from SQL Server 2017 onwards) or using theFOR XML PATHmethod for earlier versions. Here are examples of both methods.Using
STRING_AGG(SQL Server 2017+)Suppose you have a table
your_tablewith a columnyour_column, and you want to concatenate all the values inyour_columninto a single string:Using
FOR XML PATH(SQL Server 2016 and earlier)If you're using a version of SQL Server before 2017, you can achieve the same result using the
FOR XML PATHmethod:Explanation
STRING_AGGmethod:STRING_AGG(your_column, ', '): Concatenates the values ofyour_columnwith a comma and a space as the separator.FOR XML PATHmethod:(SELECT ', ' + your_column FROM your_table FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'): Creates an XML string of the concatenated values, each prefixed with a comma and a space.STUFF(..., 1, 2, ''): Removes the first comma and space from the concatenated string.Read more
Explain the SQL CURSOR with an example.
How can I optimize SQL Server queries to improve performance?
How do I handle NULL values in SQL Server queries and avoid
SQL Query to Get Yearly Aggregated Data in SQL Server